import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // 新增：用于屏幕方向控制
import 'package:video_player/video_player.dart';
import 'package:talk/pages/device/x_device_router.dart';
import 'package:talk/tools/widgets/my_app_bar.dart';
import 'package:talk/api/DeviceApi.dart';
import 'package:talk/api/BackApi.dart';
import 'package:talk/commponets/DropDownDevicePicker.dart';
import 'package:talk/routers/fluro_navigator.dart';
import 'package:talk/utils/toast_utils.dart';
import 'package:talk/pages/sip/call/sip_call.dart';
import 'package:talk/pages/device/model/Device.dart';
import 'package:path_provider/path_provider.dart';

import '../../commponets/CustomDatePicker.dart';
import '../../home/AppLocale.dart';

class DeviceBackPage extends StatefulWidget {
  const DeviceBackPage({
    Key? key,
    this.deviceId,
    this.type,
    this.sum,
    this.isScan = false,
    this.isSipInitialized,
    this.isRegistered,
  }) : super(key: key);

  final int? deviceId;
  final int? type;
  final int? sum;
  final bool isScan;
  final bool? isSipInitialized;
  final bool? isRegistered;

  @override
  State<DeviceBackPage> createState() => _DeviceBackPageState();
}

class _DeviceBackPageState extends State<DeviceBackPage> {
  // 移除固定视频高度，改为自适应
  late double _videoAspectRatio = 16 / 9; // 默认宽高比

  late int _type;
  late String _statusText;
  late Color _statusColor;
  int? deviceType;
  late int _deviceId;
  Device? _device;
  late Future<Device?> _deviceFuture;

  late bool _isSipInitialized;
  late bool _isRegistered;
  String _localDeviceModel = "RM-1-1-1-1-1-1";
  String _callDeviceModel = "";
  String _deviceName = "";

  // 视频控制器
  late VideoPlayerController _videoController;
  bool _isVideoInitialized = false;
  late Timer _timer;

  // 数据相关
  Map<String, dynamic> _videoData = {};
  List<String> _dates = [];
  List<String> _weeks = [];
  List<String> _visitorTimes = [];
  List<String> _motionTimes = [];
  String _totalDuration = "00:00";
  int _selectedDateIndex = 0;

  // 播放速度选项
  final List<double> _playbackRates = [0.5, 1.0, 1.5, 2.0];
  double _currentRate = 1.0;

  // 音量选项 (0, 20, 40, 60, 80, 100)
  final List<int> _volumeLevels = [0, 20, 40, 60, 80, 100];
  int _currentVolume = 100;

  final DeviceApi _deviceApi = DeviceApi();
  final BackApi _backApi = BackApi();

  // 用于日期选择栏滚动到最右侧
  final ScrollController _dateScrollController = ScrollController();

  // 新增：保存进入全屏前的屏幕方向
  Orientation? _previousOrientation;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _isSipInitialized = widget.isSipInitialized!;
    _isRegistered = widget.isRegistered!;

    _type = widget.type ?? 1;
    _statusText = _type == 1 ? '在线' : '离线';
    _statusColor = _type == 1 ? Colors.green : Colors.grey;
    deviceType = null;

    // 初始化视频控制器
    _initializeVideoPlayer();

    // 获取视频数据
    _getData();

    _deviceFuture = _fetchData();

    // 初始化定时器，每秒更新一次UI
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_isVideoInitialized && _videoController.value.isPlaying) {
        setState(() {});
      }
    });
  }

  Future<void> _getData() async {
    final toUpdate = {
      "deviceId": 3,
    };
    final response = await _backApi.getBackData(toUpdate);
    if (response.code == 200) {
      setState(() {
        _videoData = response.data;
        _dates = List<String>.from(_videoData['date'] ?? []);
        _weeks = List<String>.from(_videoData['week'] ?? []);
        _visitorTimes = List<String>.from(_videoData['visitor'] ?? []);
        _motionTimes = List<String>.from(_videoData['motion'] ?? []);
        _totalDuration = _videoData['urlTime'] ?? "00:00";

        if (_videoData.containsKey('url') && _videoData['url'].isNotEmpty) {
          _updateVideoSource(_videoData['url']);
        }

        if (_dates.isNotEmpty) {
          _selectedDateIndex = _dates.length - 1;
          // 延迟滚动到最右侧
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (_dateScrollController.hasClients) {
              _dateScrollController.jumpTo(_dateScrollController.position.maxScrollExtent);
            }
          });
        }
      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }

  Future<void> _updateVideoSource(String url) async {
    await _videoController.dispose();

    // _videoController = VideoPlayerController.networkUrl(
    //   Uri.parse(url),
    _videoController = VideoPlayerController.asset(
      'images/images/video/b.mp4',
      videoPlayerOptions: VideoPlayerOptions(
        mixWithOthers: false,
      ),
    );

    _videoController.addListener(() {
      if (_videoController.value.isInitialized && !_isVideoInitialized) {
        setState(() {
          _isVideoInitialized = true;
          // 更新视频宽高比
          _videoAspectRatio = _videoController.value.aspectRatio;
        });
      }

      if (_videoController.value.hasError) {
        Toast.show("视频播放错误: ${_videoController.value.errorDescription ?? '未知错误'}");
      }
    });

    try {
      await _videoController.initialize();
      _videoController.setLooping(true);
      await _videoController.play();
      // 设置初始音量
      _videoController.setVolume(_currentVolume / 100);
    } catch (e) {
      Toast.show("视频初始化失败: ${e.toString()}");
      print("视频初始化错误: $e");
    }
  }

  Future<void> _initializeVideoPlayer() async {
    _videoController = VideoPlayerController.asset(
      'images/images/video/b.mp4',
    );

    _videoController.addListener(() {
      if (_videoController.value.isInitialized && !_isVideoInitialized) {
        setState(() {
          _isVideoInitialized = true;
          // 更新视频宽高比
          _videoAspectRatio = _videoController.value.aspectRatio;
        });
      }

      if (_videoController.value.hasError) {
        Toast.show("视频播放错误: ${_videoController.value.errorDescription ?? '未知错误'}");
      }
    });

    try {
      await _videoController.initialize();
      _videoController.setLooping(true);
      await _videoController.play();
      // 设置初始音量
      _videoController.setVolume(_currentVolume / 100);
    } catch (e) {
      Toast.show("视频初始化失败: ${e.toString()}");
      print("视频初始化错误: $e");
    }
  }

  Future<Device?> _fetchData() async {
    try {
      final response = await _deviceApi.getDeviceInfo(_deviceId);
      if (response.code == 200) {
        final device = Device.fromJson(response.data);
        _callDeviceModel = device.deviceModel!;
        setState(() {
          _deviceName = device.deviceName!;
        });
        return device;
      } else {
        Toast.show(AppLocale.text('d_huoquyonghuyichang'));
        return null;
      }
    } catch (e) {
      Toast.show(AppLocale.text('d_jiazaishibai') + "${e.toString()}");
      return null;
    }
  }

  void _togglePlayPause() {
    setState(() {
      if (_videoController.value.isPlaying) {
        _videoController.pause();
      } else {
        _videoController.play();
      }
    });
  }

  void _takeScreenshot() async {
    Toast.show("截图功能待实现");
  }

  void _handleClip() {
    Toast.show("剪辑功能待实现");
  }

  void _changePlaybackRate(double rate) {
    setState(() {
      _currentRate = rate;
      _videoController.setPlaybackSpeed(rate);
    });
  }

  void _changeVolume(int volume) {
    setState(() {
      _currentVolume = volume;
      _videoController.setVolume(volume / 100);
    });
  }

  // 日期按钮点击事件
  void _onDateButtonClicked() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return CustomDatePicker(
          backgroundColor: Colors.white,
          title: "选择日期",
          titleAlignment: Alignment.center,
          maxHeight: 700,
          autoConfirm: true,
          isRange: false,
          onSelected: (startDate, endDate) {
            print(startDate);
          },
        );
      },
    );
  }

  int _timeToSeconds(String timeStr) {
    List<String> parts = timeStr.split(':');
    if (parts.length != 2) return 0;

    try {
      int minutes = int.parse(parts[0]);
      int seconds = int.parse(parts[1]);
      return minutes * 60 + seconds;
    } catch (e) {
      return 0;
    }
  }

  String _secondsToTime(int seconds) {
    int minutes = seconds ~/ 60;
    int secs = seconds % 60;
    return "${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}";
  }

  void _seekToTime(String timeStr) {
    int seconds = _timeToSeconds(timeStr);
    _videoController.seekTo(Duration(seconds: seconds));

    if (!_videoController.value.isPlaying) {
      _videoController.play();
    }
  }

  List<Map<String, int>> _parseTimeIntervals(List<String> intervals) {
    List<Map<String, int>> result = [];

    for (String interval in intervals) {
      List<String> parts = interval.split('-');
      if (parts.length == 2) {
        result.add({
          'start': _timeToSeconds(parts[0]),
          'end': _timeToSeconds(parts[1])
        });
      }
    }

    return result;
  }

  int _getTotalSeconds() {
    return _timeToSeconds(_totalDuration);
  }

  // 生成5个时间点
  List<String> _generateTimeMarkers() {
    List<String> markers = [];
    int totalSecs = _getTotalSeconds();

    if (totalSecs <= 0) {
      return ["00:00"];
    }

    // 计算间隔
    int interval = totalSecs ~/ 4; // 分成5个点，所以是4个间隔

    for (int i = 0; i < 5; i++) {
      int secs = i * interval;
      // 确保最后一个点是总时长
      if (i == 4) {
        secs = totalSecs;
      }
      markers.add(_secondsToTime(secs));
    }

    return markers;
  }

  // 新增：进入全屏方法
  void _enterFullScreen() async {
    // 保存当前屏幕方向
    _previousOrientation = MediaQuery.of(context).orientation;

    // 强制横屏
    await SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);

    // 隐藏状态栏和导航栏
    await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

    // 导航到全屏页面
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => _FullScreenVideoPage(
          controller: _videoController,
          onExit: _exitFullScreen,
        ),
      ),
    );
  }

  // 新增：退出全屏方法
  void _exitFullScreen() async {
    // 恢复之前的屏幕方向
    if (_previousOrientation == Orientation.portrait) {
      await SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    } else {
      await SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
    }

    // 恢复状态栏和导航栏
    await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  }

  @override
  void dispose() {
    _videoController.dispose();
    _timer.cancel();
    _dateScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_kaihuifang'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
        buttonAlignment: MainAxisAlignment.end,
        contentAlignment: TextAlign.right,
      ),
      body: FutureBuilder<Device?>(
        future: _deviceFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
              ),
            );
          }

          if (snapshot.hasError || snapshot.data == null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    AppLocale.text('d_jiazaishebeixinxishibai'),
                    style: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => setState(() {}),
                    child: Text(AppLocale.text('d_chognshi')),
                  ),
                ],
              ),
            );
          }

          _device = snapshot.data;
          return Column(
            children: [
              const SizedBox(height: 20),

              // 视频区域（使用AspectRatio根据宽高比自适应）
              AspectRatio(
                aspectRatio: _videoAspectRatio,
                child: Stack(
                  children: [
                    // 视频播放区域（无额外容器和间距）
                    Positioned.fill(
                      child: _buildVideoGrid(),
                    ),

                    // 视频时间显示（左上角）
                    if (_isVideoInitialized)
                      Positioned(
                        top: 8,
                        left: 8,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                          color: Colors.black54,
                          child: Text(
                            "${_formatDuration(_videoController.value.position)} / $_totalDuration",
                            style: const TextStyle(color: Colors.white, fontSize: 11),
                          ),
                        ),
                      ),

                    // 右侧垂直按钮（截图、剪辑、全屏）
                    Positioned(
                      right: 6,
                      top: 8,
                      child: Column(
                        children: [
                          _buildActionButton(
                            Icons.camera_alt,
                            AppLocale.text('d_jietu'),
                            onTap: _takeScreenshot,
                          ),
                          const SizedBox(height: 8),
                          _buildActionButton(
                            Icons.cut,
                            AppLocale.text('d_jianji'),
                            onTap: _handleClip,
                          ),
                          const SizedBox(height: 8),
                          _buildActionButton(
                            Icons.fullscreen,
                            AppLocale.text('d_quanping'),
                            onTap: _enterFullScreen, // 修改：使用新的全屏方法
                          ),
                        ],
                      ),
                    ),

                    // 下方水平按钮（播放/暂停、速度、音量）
                    Positioned(
                      left: 8,
                      bottom: 8,
                      child: Row(
                        children: [
                          _buildActionButton(
                              _videoController.value.isPlaying ? Icons.pause : Icons.play_arrow,
                              _videoController.value.isPlaying ? AppLocale.text('d_zanting') : AppLocale.text('d_bofang'),
                              onTap: _togglePlayPause,
                              isHorizontal: true
                          ),
                          const SizedBox(width: 8),
                          _buildSpeedDropdown(),
                          const SizedBox(width: 8),
                          _buildVolumeDropdown(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              // 日期选择栏（与视频区域紧密贴合，无间隔）
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                color: Colors.white,
                child: SingleChildScrollView(
                    controller: _dateScrollController,
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        Row(
                          children: List.generate(_dates.length, (index) {
                            bool isSelected = index == _selectedDateIndex;
                            return GestureDetector(
                              onTap: () {
                                setState(() {
                                  _selectedDateIndex = index;
                                });
                              },
                              child: Container(
                                width: 50,
                                padding: const EdgeInsets.symmetric(vertical: 6),
                                margin: const EdgeInsets.symmetric(horizontal: 4),
                                decoration: BoxDecoration(
                                  color: isSelected ? Colors.blue : Colors.transparent,
                                  borderRadius: BorderRadius.circular(20),
                                ),
                                child: Column(
                                  children: [
                                    Text(
                                      _weeks[index],
                                      style: TextStyle(
                                        color: isSelected ? Colors.white : Colors.grey,
                                        fontSize: 12,
                                      ),
                                    ),
                                    const SizedBox(height: 2),
                                    Text(
                                      _dates[index],
                                      style: TextStyle(
                                        color: isSelected ? Colors.white : Colors.black,
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }),
                        ),

                        const SizedBox(width: 15),

                        //日期按钮 - 添加了点击事件
                        GestureDetector(
                          onTap: _onDateButtonClicked,
                          child: Container(
                            child: Image.asset(
                                "images/images/message/t2.png",
                                width: 30
                            ),
                          ),
                        )
                      ],
                    )
                ),
              ),

              // 时间轴进度条
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                color: Colors.white,
                child: Column(
                  children: [
                    const SizedBox(height: 6),

                    // 进度条区域
                    Column(
                      children: [
                        const SizedBox(height: 1),

                        // 进度条
                        Container(
                          height: 36, // 增加高度
                          child: GestureDetector(
                            onTapDown: (TapDownDetails details) {
                              RenderBox renderBox = context.findRenderObject() as RenderBox;
                              Offset localPosition = renderBox.globalToLocal(details.globalPosition);
                              final painter = TimelinePainter(
                                visitorIntervals: _parseTimeIntervals(_visitorTimes),
                                motionIntervals: _parseTimeIntervals(_motionTimes),
                                totalSeconds: _getTotalSeconds(),
                                currentPosition: _isVideoInitialized
                                    ? _videoController.value.position.inSeconds
                                    : 0,
                                onIntervalTapped: (startSeconds) {
                                  _seekToTime(_secondsToTime(startSeconds));
                                },
                              );
                              painter.handleTap(localPosition, renderBox.size);
                            },
                            child: CustomPaint(
                              size: Size.infinite,
                              painter: TimelinePainter(
                                visitorIntervals: _parseTimeIntervals(_visitorTimes),
                                motionIntervals: _parseTimeIntervals(_motionTimes),
                                totalSeconds: _getTotalSeconds(),
                                currentPosition: _isVideoInitialized
                                    ? _videoController.value.position.inSeconds
                                    : 0,
                                onIntervalTapped: (startSeconds) {
                                  _seekToTime(_secondsToTime(startSeconds));
                                },
                                timeMarkers: _generateTimeMarkers(),
                              ),
                            ),
                          ),
                        ),

                        // 刻度线
                        Container(
                          height: 8,
                          child: CustomPaint(
                            size: Size.infinite,
                            painter: TimelineTicksPainter(
                              totalSeconds: _getTotalSeconds(),
                              timeMarkers: _generateTimeMarkers(),
                            ),
                          ),
                        ),
                      ],
                    ),

                    // 时间标记
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: _generateTimeMarkers().map((time) {
                        return Text(
                            time,
                            style: const TextStyle(fontSize: 11, color: Colors.grey)
                        );
                      }).toList(),
                    ),

                    const SizedBox(height: 20),

                    // 时间轴说明
                    Row(
                      //居中
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 30,
                          height: 16,
                          margin: const EdgeInsets.only(right: 4),
                          decoration: BoxDecoration(
                            color: Colors.green,
                            borderRadius: BorderRadius.circular(3),
                          ),
                        ),
                        Text(
                            AppLocale.text('d_fangkehujiao2'),
                            style: TextStyle(
                                fontSize: 11
                            )
                        ),
                        const SizedBox(width: 30),
                        Container(
                          width: 30,
                          height: 16,
                          margin: const EdgeInsets.only(right: 4),
                          decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(3),
                          ),
                        ),
                        Text(
                            AppLocale.text('d_yidongzhence2'),
                            style: TextStyle(
                                fontSize: 11
                            )
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // 播放速度下拉框
  Widget _buildSpeedDropdown() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        DropdownButton<double>(
          value: _currentRate,
          items: _playbackRates.map((rate) {
            return DropdownMenuItem<double>(
              value: rate,
              child: Text(
                "${rate}x",
                style: const TextStyle(color: Colors.white, fontSize: 11),
              ),
            );
          }).toList(),
          onChanged: (value) {
            if (value != null) {
              _changePlaybackRate(value);
            }
          },
          underline: Container(),
          dropdownColor: Colors.black54,
          iconSize: 14,
        ),
      ],
    );
  }

  // 音量控制下拉框
  Widget _buildVolumeDropdown() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        DropdownButton<int>(
          value: _currentVolume,
          items: _volumeLevels.map((volume) {
            return DropdownMenuItem<int>(
              value: volume,
              child: Text(
                "${volume}%",
                style: const TextStyle(color: Colors.white, fontSize: 11),
              ),
            );
          }).toList(),
          onChanged: (value) {
            if (value != null) {
              _changeVolume(value);
            }
          },
          underline: Container(),
          dropdownColor: Colors.black54,
          iconSize: 14,
        ),
      ],
    );
  }

  // 视频区域
  Widget _buildVideoGrid() {
    return RepaintBoundary(
      child: Container(
          padding: EdgeInsets.zero,
          margin: EdgeInsets.zero,
          child: _buildSingleVideo()
      ),
    );
  }

  // 构建单个视频区域
  Widget _buildSingleVideo() {
    return Container(
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      color: Colors.black, // 视频加载前显示黑色背景，而不是灰色
      child: Stack(
        children: [
          // 视频播放器
          if (_isVideoInitialized)
            Positioned.fill(
              child: VideoPlayer(_videoController),
            )
          else if (_videoController.value.hasError)
            Center(
              child: Text(
                AppLocale.text('d_shipinjiazaishibai'),
                style: TextStyle(color: Colors.red, fontSize: 14),
              ),
            )
          else
            const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
              ),
            ),

          // 暂停状态下显示大的播放按钮
          if (!_videoController.value.isPlaying)
            Positioned.fill(
              child: Center(
                child: Icon(
                  Icons.play_arrow,
                  color: Colors.white54,
                  size: 50,
                ),
              ),
            ),
        ],
      ),
    );
  }

  // 格式化视频时长
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final second = twoDigits(duration.inSeconds.remainder(60));
    return [minutes, second].join(':');
  }

  // 构建功能按钮
  Widget _buildActionButton(IconData icon, String text,
      {VoidCallback? onTap, bool isHorizontal = false}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(6),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: Colors.black54,
              borderRadius: BorderRadius.circular(16),
            ),
            child: Center(
              child: Icon(
                icon,
                color: Colors.white,
                size: 16,
              ),
            ),
          ),
          const SizedBox(height: 10),
        ],
      ),
    );
  }
}

// 新增：全屏视频页面
// 修改全屏视频页面为StatefulWidget以支持状态更新
class _FullScreenVideoPage extends StatefulWidget {
  final VideoPlayerController controller;
  final VoidCallback onExit;

  const _FullScreenVideoPage({
    required this.controller,
    required this.onExit,
  });

  @override
  State<_FullScreenVideoPage> createState() => _FullScreenVideoPageState();
}

class _FullScreenVideoPageState extends State<_FullScreenVideoPage> {
  late VoidCallback _listener;

  @override
  void initState() {
    super.initState();
    // 创建监听器，当视频状态变化时更新UI
    _listener = () {
      setState(() {});
    };

    // 添加监听器
    widget.controller.addListener(_listener);
  }

  @override
  void dispose() {
    // 移除监听器，防止内存泄漏
    widget.controller.removeListener(_listener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        widget.onExit();
        return true;
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Stack(
          children: [
            Positioned.fill(
              child: Center(
                child: AspectRatio(
                  aspectRatio: widget.controller.value.aspectRatio,
                  child: VideoPlayer(widget.controller),
                ),
              ),
            ),

            Positioned(
              top: 20,
              right: 20,
              child: IconButton(
                icon: const Icon(
                  Icons.fullscreen_exit,
                  color: Colors.white,
                  size: 24,
                ),
                onPressed: () {
                  Navigator.pop(context);
                  widget.onExit();
                },
              ),
            ),

            Positioned(
              bottom: 40,
              left: 0,
              right: 0,
              child: Center(
                child: IconButton(
                  icon: Icon(
                    // 根据视频实际播放状态显示对应图标
                    widget.controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
                    color: Colors.white,
                    size: 48,
                  ),
                  onPressed: () {
                    if (widget.controller.value.isPlaying) {
                      widget.controller.pause();
                    } else {
                      widget.controller.play();
                    }
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}


// 自定义时间轴绘制器
class TimelinePainter extends CustomPainter {
  final List<Map<String, int>> visitorIntervals;
  final List<Map<String, int>> motionIntervals;
  final int totalSeconds;
  final int currentPosition;
  final Function(int) onIntervalTapped;
  final List<String> timeMarkers;

  TimelinePainter({
    required this.visitorIntervals,
    required this.motionIntervals,
    required this.totalSeconds,
    required this.currentPosition,
    required this.onIntervalTapped,
    this.timeMarkers = const [],
  }) : super(repaint: null);

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制背景 - 更美观的样式
    final backgroundPaint = Paint()
      ..color = Colors.grey[200]!
      ..style = PaintingStyle.fill;
    canvas.drawRRect(
      RRect.fromRectAndRadius(
        Rect.fromLTWH(0, 5, size.width, size.height - 10),
        const Radius.circular(5),
      ),
      backgroundPaint,
    );

    // 绘制分隔线
    final linePaint = Paint()
      ..color = Colors.grey[300]!
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;
    canvas.drawLine(
        Offset(0, size.height / 2),
        Offset(size.width, size.height / 2),
        linePaint
    );

    // 如果总时长为0，不绘制其他内容
    if (totalSeconds == 0) return;

    // 绘制访客呼叫区间（绿色）- 增加高度
    final visitorPaint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.fill;

    for (var interval in visitorIntervals) {
      double startX = (interval['start']! / totalSeconds) * size.width;
      double width = ((interval['end']! - interval['start']!) / totalSeconds) * size.width;

      // 确保宽度不为负
      width = max(2, width);

      canvas.drawRRect(
        RRect.fromRectAndRadius(
          Rect.fromLTWH(startX, 5, width, size.height - 10),
          const Radius.circular(3),
        ),
        visitorPaint,
      );
    }

    // 绘制移动侦测区间（蓝色）- 增加高度
    final motionPaint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.fill;

    for (var interval in motionIntervals) {
      double startX = (interval['start']! / totalSeconds) * size.width;
      double width = ((interval['end']! - interval['start']!) / totalSeconds) * size.width;

      width = max(2, width);

      canvas.drawRRect(
        RRect.fromRectAndRadius(
          Rect.fromLTWH(startX, 5, width, size.height - 10),
          const Radius.circular(3),
        ),
        motionPaint,
      );
    }

    // 绘制当前位置指示器 - 更美观的样式
    final indicatorPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    double indicatorX = (currentPosition / totalSeconds) * size.width;

    // 绘制指示器阴影
    final shadowPaint = Paint()
      ..color = Colors.red.withOpacity(0.3)
      ..style = PaintingStyle.fill;
    canvas.drawCircle(
      Offset(indicatorX, size.height / 2),
      7,
      shadowPaint,
    );

    // 绘制指示器圆点
    canvas.drawCircle(
      Offset(indicatorX, size.height / 2),
      5,
      indicatorPaint,
    );

    // 绘制指示器中心线
    final indicatorLinePaint = Paint()
      ..color = Colors.red
      ..strokeWidth = 1.5
      ..style = PaintingStyle.stroke;

    canvas.drawLine(
        Offset(indicatorX, 0),
        Offset(indicatorX, size.height),
        indicatorLinePaint
    );
  }

  @override
  bool shouldRepaint(covariant TimelinePainter oldDelegate) {
    return visitorIntervals != oldDelegate.visitorIntervals ||
        motionIntervals != oldDelegate.motionIntervals ||
        totalSeconds != oldDelegate.totalSeconds ||
        currentPosition != oldDelegate.currentPosition ||
        timeMarkers != oldDelegate.timeMarkers;
  }

  // 处理点击事件的方法
  void handleTap(Offset position, Size size) {
    if (totalSeconds == 0) return;

    double tappedX = position.dx;
    int tappedSeconds = (tappedX / size.width * totalSeconds).round();

    // 检查是否点击了某个区间
    for (var interval in [...visitorIntervals, ...motionIntervals]) {
      if (tappedSeconds >= interval['start']! && tappedSeconds <= interval['end']!) {
        onIntervalTapped(interval['start']!);
        return;
      }
    }

    // 如果没点击区间，直接跳转到点击位置
    onIntervalTapped(tappedSeconds);
  }
}

// 时间轴刻度绘制器
class TimelineTicksPainter extends CustomPainter {
  final int totalSeconds;
  final List<String> timeMarkers;

  TimelineTicksPainter({
    required this.totalSeconds,
    required this.timeMarkers,
  }) : super(repaint: null);

  @override
  void paint(Canvas canvas, Size size) {
    if (totalSeconds <= 0 || timeMarkers.isEmpty) return;

    // 刻度线画笔
    final tickPaint = Paint()
      ..color = Colors.grey[400]!
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    // 绘制主刻度线（每个时间标记处）
    for (int i = 0; i < timeMarkers.length; i++) {
      double x = (i / (timeMarkers.length - 1)) * size.width;

      // 主刻度线
      canvas.drawLine(
          Offset(x, 0),
          Offset(x, size.height * 0.7),
          tickPaint
      );
    }

    // 绘制次要刻度线
    final smallTickPaint = Paint()
      ..color = Colors.grey[300]!
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    // 在每个主要刻度之间添加3个次要刻度
    for (int i = 0; i < timeMarkers.length - 1; i++) {
      double startX = (i / (timeMarkers.length - 1)) * size.width;
      double endX = ((i + 1) / (timeMarkers.length - 1)) * size.width;
      double interval = (endX - startX) / 4;

      for (int j = 1; j < 4; j++) {
        double x = startX + interval * j;
        canvas.drawLine(
            Offset(x, size.height * 0.3),
            Offset(x, size.height * 0.7),
            smallTickPaint
        );
      }
    }
  }

  @override
  bool shouldRepaint(covariant TimelineTicksPainter oldDelegate) {
    return totalSeconds != oldDelegate.totalSeconds ||
        timeMarkers != oldDelegate.timeMarkers;
  }
}


